package com.miaosha.ms_03.service;

import com.miaosha.ms_03.SystemConstant;
import com.miaosha.ms_03.dao.MiaoshaOrderDao;
import com.miaosha.ms_03.domain.Goods;
import com.miaosha.ms_03.domain.MiaoshaOrder;
import com.miaosha.ms_03.domain.OrderInfo;
import com.miaosha.ms_03.domain.User;
import com.miaosha.ms_03.exception.GlobalException;
import com.miaosha.ms_03.result.CodeMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @Description //TODO
 * @Author Administrator
 * @DATE 2020/9/19 21:22
 **/
@Service
public class MiaoshaService {

    private Logger logger = LoggerFactory.getLogger(MiaoshaService.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsService goodsService;

    @Resource
    private MiaoshaOrderDao miaoshaOrderDao;

    @Transactional
    public OrderInfo buyGoods(Goods goods, User user) {
        if (user == null) {
            throw new GlobalException(CodeMsg.USER_EMPTY);
        }
        Long userId = user.getId();
        Long goodsId = goods.getId();
        if(goods == null || goodsId == null){
            throw new GlobalException(CodeMsg.GOOD_ID_EMPTY);
        }
        //校验是否该用户已经秒杀过该商品
        if(!orderService.repeatOrderByUserIdAndGoodsId(userId,goodsId)){
            throw new GlobalException(CodeMsg.ORDER_REPEAT);
        }
        //获取商品详情
        String goodsName = goods.getGoodsName();
        BigDecimal goodsPrice = goods.getGoodsPrice();

        //1.减去商品库存
        goods.setGoodsStock(goods.getGoodsStock() - 1);
        goodsService.updateStock(goods);
        logger.info("成功减去库存，商品ID ={}",goodsId);
        //2. 生成订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(1L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goodsId);
        orderInfo.setGoodsName(goodsName);
        orderInfo.setGoodsPrice(goodsPrice);
        orderInfo.setOrderChannel(SystemConstant.OrderChannel.PC.getCode());
        orderInfo.setUserId(userId);
        orderInfo.setStatus(SystemConstant.OrderStatusEnum.NEW.getCode());
        orderInfo = orderService.insert(orderInfo);
        logger.info("----成功生成订单信息 订单ID={}",orderInfo.getId());
        //3.生成秒杀订单
        MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
        miaoshaOrder.setGoodsId(goodsId);
        miaoshaOrder.setOrderId(orderInfo.getId());
        miaoshaOrder.setUserId(userId);
        miaoshaOrderDao.insert(miaoshaOrder);
        logger.info("----成功生成秒杀订单信息 订单ID={}",miaoshaOrder.getId());
        return orderInfo;
    }
}
